package atomic;

import jdk.nashorn.internal.objects.annotations.Getter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fei
 * @date 2023/1/17 17:31
 * @description
 */
public class AtomicIntegerDemo {

    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        // 初始 100
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 1; i <=100; i++) {
            new Thread(() -> {
                try
                {
                    for (int j = 1; j <=5000; j++)
                    {
                        myNumber.addPlusPlus();
                    }
                }finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }
        // 暂停几秒，输出才会是 全部线程处理完成后的值，但是如果是用 tsleep ，如果不知道几秒能处理完成怎么办，所以才会用下面那个
        // try{ TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) { e.printStackTrace(); }

        // 当初始值递减到 0时，才可以继续往下面走
        countDownLatch.await();

        System.out.println(myNumber.getAtomicInteger().get());
    }

}

class MyNumber {
    private AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlusPlus() {
        atomicInteger.incrementAndGet();
    }

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }
}